package com.example.mobifin_busticket.views.dialogs;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.mobifin_busticket.AESEncoder;
import com.example.mobifin_busticket.AppData;
import com.example.mobifin_busticket.MD5Generator;
import com.example.mobifin_busticket.MyApplication;
import com.example.mobifin_busticket.R;
import com.example.mobifin_busticket.UserInfo;
import com.example.mobifin_busticket.controller.databasemanager.DatabaseManager;

public class Registration_Process extends Dialog implements
		android.view.View.OnClickListener {
	SQLiteDatabase db;

	EditText edt_tno, edt_pass, edt_pin;
	Button ok, cncle;
	Context context;
	Handler handler = new Handler();
	String kycinfo, no, mail, terminalRequestID;
	JSONObject response = new JSONObject();

	public Registration_Process(Context mcontext, String kycinfo, String no,
			String mail, String terminalRequestID) {
		// TODO Auto-generated constructor stub
		// TODO Auto-generated method stub
		super(mcontext);
		context = mcontext;
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.registration_process);
		edt_tno = (EditText) findViewById(R.id.txttno);
		edt_pass = (EditText) findViewById(R.id.txtpass);
		edt_pin = (EditText) findViewById(R.id.txtt_pin);
		ok = (Button) findViewById(R.id.btn_ok);
		cncle = (Button) findViewById(R.id.btn_Cancel);
		ok.setOnClickListener(this);
		this.kycinfo = kycinfo;
		this.no = no;
		this.mail = mail;
		this.terminalRequestID = terminalRequestID;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (validation_chk() == true) {

			MyApplication.showProgressDialog(context, "Please Wait");
			new Thread() {
				@Override
				public void run() {
					super.run();
					int what = 0;
					try {
						String reponseString = makeHttpConnectionWithHSM(
								context, AppData.hsm_hostURL,
								terminalRequestID, edt_tno.getText().toString());
						response = new JSONObject(reponseString);
					} catch (Exception e) {
						// TODO: handle exception
						what = 1;
						e.printStackTrace();
					}
					mHandler.sendEmptyMessage(what);
				}
			}.start();
			dismiss();
		}
	}

	private String getQuery(List<NameValuePair> params)
			throws UnsupportedEncodingException {
		StringBuilder result = new StringBuilder();
		boolean first = true;

		for (NameValuePair pair : params) {
			if (first)
				first = false;
			else
				result.append("&");

			result.append(pair.getName());
			result.append("=");
			result.append(pair.getValue());
		}

		return result.toString();
	}

	private Handler mHandler = new Handler() {

		String responseCode, responseDesc;

		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// mProgress.dismiss();
			if (msg.what == 1) {
				return;
			} else {
				Log.i("Response", response.toString());
				if (response.length() > 0) {
					try {
						responseCode = response.getString("ResponseCode");
						responseDesc = response
								.getString("ResponseDescription");
					} catch (JSONException e) {
						e.printStackTrace();
					}

					if (responseCode.equals("000")) {
						try {
							if (!response.getString("EncryptionKey").equals(
									null)
									&& response.getString("EncryptionKey")
											.length() > 0) {
								String terminalNumber, encryptionKey;

								terminalNumber = edt_tno.getText().toString();
								encryptionKey = response
										.getString("EncryptionKey");
								UserInfo userinfo = new UserInfo();
								userinfo.setLoginPin(edt_pass.getText()
										.toString().trim());

								userinfo.setTransactionPassword((edt_pin
										.getText().toString().trim()));
//mane peli screen ma enc key lai aap
								//userinfo mathi get kare to
								//uesrinfo appdata ma set karavelu 6e..ok let me chk
								userinfo.setTerminalNumber(terminalNumber);
								userinfo.setTerminalRequestID(terminalRequestID);
								userinfo.setEncryptionKey(encryptionKey);
								AppData.setUserInfo(userinfo);
								DatabaseManager dbManager = new DatabaseManager(
										context);

								dbManager.flushTable();
								dbManager = null;
								dbManager = new DatabaseManager(context);

								dbManager.insertUserInfo(kycinfo, no, mail,
										edt_tno.getText().toString(), edt_pass
												.getText().toString(), edt_pin
												.getText().toString(), userinfo
												.getTerminalNumber(), userinfo
												.getEncryptionKey());

								dbManager.close();
								Toast.makeText(context,
										"Credentials added successfully",
										Toast.LENGTH_LONG).show();

								MyApplication.dismissProgressDialog();
							}
							dismiss();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					} else {
						handler.post(new Runnable() {
							public void run() {
								Toast.makeText(context, responseDesc,
										Toast.LENGTH_LONG).show();
								MyApplication.dismissProgressDialog();
							}
						});
					}
				}
			}
		}
	};

	public String makeHttpConnectionWithHSM(final Context context, String URL,
			String terminalRequestID, String terminalNumber)
			throws MalformedURLException, IOException {
		StringBuffer sb = null;
		String response = "", returnResponse = "", clientInfo = "";

		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		clientInfo = "Android" + "," + "," + android.os.Build.MODEL + ","
				+ android.os.Build.ID + "," + display.getWidth() + "x"
				+ display.getHeight() + "," + android.os.Build.MANUFACTURER
				+ "," + android.os.Build.BOARD + "," + android.os.Build.DISPLAY
				+ "," + android.os.Build.FINGERPRINT;

		String base64 = null;
		StringBuffer buffer = new StringBuffer(terminalNumber);
		if (terminalNumber.length() < 16) {
			int shortage = 16 - terminalNumber.length();
			for (int i = 0; i < shortage; i++) {
				buffer.append("0");
			}
		}

		AESEncoder mcrypt = new AESEncoder(buffer.toString());
		try {
			base64 = mcrypt.encrypt(terminalNumber);
		} catch (Exception e2) {
			e2.printStackTrace();
		}

		if (base64 != null) {
			System.out.println("AES Encrypted Base64 string getCategoryID : "
					+ base64);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
			nameValuePair.add(new BasicNameValuePair("TerminalRequestID",
					terminalRequestID));

			// /user e enter karelo terminal number base64 ma encode kari ne
			// mokalyiye che
			nameValuePair.add(new BasicNameValuePair("TerminalNumber", base64));
			nameValuePair.add(new BasicNameValuePair("function",
					"HsmGetEncryptionKey"));

			HttpURLConnection httpcon = null;

			InputStream is = null;

			httpcon = (HttpURLConnection) ((new URL(URL).openConnection()));
			httpcon.setDoOutput(true);
			httpcon.setRequestMethod("POST");
			httpcon.setRequestProperty("Accept_Language", "en-US");
			httpcon.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			httpcon.setRequestProperty("Client", clientInfo);
			httpcon.setRequestProperty("Application_Version_Tracker",
					AppData.app_tracking_pattern);
			httpcon.setConnectTimeout(18000);
			httpcon.connect();

			System.out.println("-------Header Parameter-------");
			System.out.println("Client:" + clientInfo);
			System.out.println("Application_Version_Tracker: "
					+ AppData.app_tracking_pattern);

			OutputStream os = httpcon.getOutputStream();
			os.write(getQuery(nameValuePair).getBytes());
			os.close();

			if (httpcon.getResponseCode() == HttpURLConnection.HTTP_OK) {
				is = httpcon.getInputStream();

				sb = new StringBuffer();
				int chr;
				while ((chr = is.read()) != -1) {
					sb.append((char) chr);
				}

				try {
					response = sb.toString();
					System.out.println("Result:" + response);
				} catch (Exception e) {
					e.printStackTrace();
				}

				JSONObject encryptedJsonObject = null;
				try {
					encryptedJsonObject = new JSONObject(response);
				} catch (JSONException e) {
					e.printStackTrace();
				}

				byte[] decryptedData = null;
				try {
					decryptedData = mcrypt.decrypt(encryptedJsonObject
							.getString("EncryptionKey"));
				} catch (Exception e1) {
					e1.printStackTrace();
				}

				try {
					if (encryptedJsonObject.has("EncryptionKey")) {
						encryptedJsonObject.put("EncryptionKey", new String(
								decryptedData));
					}

					System.out.println("Descrypted:"
							+ encryptedJsonObject.toString());
					returnResponse = encryptedJsonObject.toString();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (NullPointerException e) {
					e.printStackTrace();
				}
			} else if (httpcon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
				JSONObject jsonObject = null;
				try {
					jsonObject = new JSONObject();
					jsonObject.put("ResponseCode", "HTTP401");
					jsonObject.put("ResponseDescription",
							"Connection Unauthorized");
					System.out.println("Error 401:" + jsonObject.toString());
					returnResponse = jsonObject.toString();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (httpcon.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST) {
				JSONObject jsonObject = null;
				try {
					jsonObject = new JSONObject();
					jsonObject.put("ResponseCode", "HTTP400");
					jsonObject.put("ResponseDescription", "Http Bad Request");
					System.out.println("Error 400:" + jsonObject.toString());
					returnResponse = jsonObject.toString();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (httpcon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
				JSONObject jsonObject = null;
				try {
					jsonObject = new JSONObject();
					jsonObject.put("ResponseCode", "HTTP500");
					jsonObject.put("ResponseDescription",
							"Http Internal Error occurred");
					System.out.println("Error 500:" + jsonObject.toString());
					returnResponse = jsonObject.toString();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (httpcon.getResponseCode() == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
				JSONObject jsonObject = null;
				try {
					jsonObject = new JSONObject();
					jsonObject.put("ResponseCode", "HTTP408");
					jsonObject.put("ResponseDescription",
							"Http Request Timeout");
					System.out.println("Error 408:" + jsonObject.toString());
					returnResponse = jsonObject.toString();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return returnResponse;
	}

	private boolean validation_chk() {
		boolean flag = true;
		String pswd = "[0-9]{6}";
		if (edt_tno.getText().toString().trim().length() == 0) {
			flag = false;
			edt_tno.setError(getContext().getResources().getString(
					R.string.valid_tno));
		}

		if (!edt_pass.getText().toString().trim().matches(pswd)) {
			flag = false;
			edt_pass.setError(getContext().getResources().getString(
					R.string.valid_Pswd));

		}
		if (edt_pin.getText().toString().trim().length() == 0) {
			flag = false;
			edt_pin.setError(getContext().getResources().getString(
					R.string.valid_pin));
		}
		return flag;
	}
}
